package com.acwing.lc.part1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author rkc
 * @date 2022/9/12 16:32
 */
public class LC40组合总和II {

    private int[] nums;
    private List<List<Integer>> ans = new ArrayList<>();
    private List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        nums = candidates;
        Arrays.sort(nums);
        dfs(0, target);
        return ans;
    }

    private void dfs(int start, int target) {
        if (target == 0) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) continue;
            if (target - nums[i] >= 0) {
                path.add(nums[i]);
                dfs(i + 1, target - nums[i]);
                path.remove(path.size() - 1);
            }
        }
    }
}
